<template>
    <div class="latest-emotion-page">
        <h2 class="title1" style="margin-bottom: 20px;">
            <el-icon :size="25">
                <DocumentRemove />
            </el-icon> 最新情绪
        </h2>
        <el-card class="box-card query-card" shadow="never" style="margin-bottom: 20px">
            <template #header>
                <div class="card-header">
                    <span>操作项</span>
                </div>
            </template>
            <div class="filter-section">
                <div class="filter-item">
                    <span>记录ID：</span>
                    <el-input v-model="filterId" placeholder="请输入记录ID" style="width: 200px" />
                </div>
                <div class="filter-item">
                    <span>情绪筛选：</span>
                    <el-select v-model="filterEmotion" placeholder="请选择情绪类型" style="width: 150px">
                        <el-option label="开心" value="happy" />
                        <el-option label="愤怒" value="angry" />
                        <el-option label="沮丧" value="sad" />
                        <el-option label="中性" value="neutral" />
                        <el-option label="惊喜" value="surprise" />
                        <el-option label="恐惧" value="fear" />
                        <el-option label="厌恶" value="disgust" />
                        <el-option label="未知" value="unknown" />
                    </el-select>
                </div>
                <div class="filter-item">
                    <el-button type="primary" @click="handleQuery">查询</el-button>
                    <el-button type="success" plain @click="handleReset">重置</el-button>
                </div>
                <div class="action-buttons">
                    <el-button type="danger" plain @click="handleBatchDelete">批量删除</el-button>
                </div>
            </div>
        </el-card>
        <!-- 数据列表 -->

        <el-card class="box-card" shadow="never" style="width:100%;box-shadow:none;border:none;">
            <template #header>
                <div class="table-header">
                    <div class="card-header">
                        <span>情绪分析记录</span>
                    </div>
                </div>
            </template>
            <!-- 新增滚动容器 -->
            <div class="table-scroll-wrapper">
                <el-table :data="filteredTableData" border style="width: 100%; margin-top: 20px;"
                    @selection-change="handleSelectionChange">
                    <el-table-column type="selection" width="60"></el-table-column>
                    <el-table-column label="序号" align="center" width="100">
                        <template #default="scope">
                            {{ scope.$index + 1 }}
                        </template>
                    </el-table-column>
                    <el-table-column prop="id" label="记录ID" align="center" width="140"></el-table-column>
                    <el-table-column prop="name" label="用户名" align="center" width="140"></el-table-column>
                    <el-table-column prop="image" label="上传图片" align="center" width="280">
                        <template #default="scope">
                            <div class="single-line-img">
                                <span v-if="scope.row.image"
                                    style="max-width:260px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;display:inline-block;">
                                    {{ scope.row.image }}
                                </span>
                                <span v-else style="color:#bbb;">无</span>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column prop="emotion_type" label="情绪类型" align="center">
                        <template #default="scope">
                            <el-tag :type="'info'" :style="getEmotionTagStyle(scope.row.emotion_type)"
                                disable-transitions>
                                {{ emotionMap[scope.row.emotion_type] || scope.row.emotion_type }}
                            </el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column prop="uploadDate" label="检测时间" align="center"></el-table-column>
                    <el-table-column label="操作" align="center" width="350">
                        <template #default="scope">
                            <el-button type="primary" size="small" @click="viewRecord(scope.row)">查看</el-button>
                            <el-button size="small" @click="showEmotion(scope.row)">
                                查看个人情绪
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>

            <!-- 分页 -->
            <div class="pagination-container">
                <el-pagination background layout="total, sizes, prev, pager, next" :total="filteredTableData.length"
                    :page-size="pageSize" :current-page="currentPage" @size-change="handleSizeChange"
                    @current-change="handleCurrentChange" />
            </div>
        </el-card>

        <!-- 查看弹窗 -->
        <el-dialog v-model="dialogVisible" title="记录信息" width="900px" top="9vh" :close-on-click-modal="false" center>
            <div class="emo-detail-content2">
                <!-- 第一行：记录ID和检测时间 -->
                <div class="emo-row emo-row-top">
                    <div class="emo-col">
                        <span class="emo-detail-label">记录ID：</span>
                        <span class="emo-detail-value">{{ currentRecord?.id }}</span>
                    </div>
                    <div class="emo-col">
                        <span class="emo-detail-label">检测时间：</span>
                        <span class="emo-detail-value">{{ currentRecord?.uploadDate }}</span>
                    </div>
                </div>
                <!-- 第二行：上传图片和雷达图 -->
                <div class="emo-row emo-row-img">
                    <div class="emo-col emo-img-col">
                        <span class="emo-detail-label">上传图片：</span>
                        <div class="emo-img-box2">
                            <img v-if="currentRecord?.image" :src="currentRecord.image" alt="图片" />
                        </div>
                    </div>
                    <div class="emo-col emo-radar-col">
                        <span class="emo-detail-label">分析结果：</span>
                        <span class="emo-detail-value">
                            <div ref="dialogRadarRef" style="width:320px;height:220px;"></div>
                        </span>

                    </div>
                </div>
                <!-- 第三行：情绪分析报告 -->
                <div class="emo-detail-row emo-detail-report">
                    <div class="emo-detail-labe">情绪分析报告：</div>
                    <div class="emo-detail-value">

                        <!-- ...existing code... -->
                        <div v-if="dialogContentHtml" class="emo-rich-content" v-html="dialogContentHtml"></div>
                        <pre v-else class="emo-json">{{ formattedReport }}</pre>
                        <!-- ...existing code... -->
                    </div>
                </div>
                <div class="emo-detail-btn2">
                    <el-button type="primary" @click="dialogVisible = false">确认/关闭</el-button>
                </div>
            </div>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted, onBeforeUnmount, computed, nextTick, watch } from 'vue'
import axios from 'axios'
import * as echarts from 'echarts'
import { ElMessageBox, ElMessage, ElNotification } from 'element-plus'
import { useRouter } from 'vue-router'
import MarkdownIt from 'markdown-it'
const dialogVisible = ref(false)

const emotionMap = {
    happy: '开心',
    angry: '愤怒',
    sad: '沮丧',
    neutral: '中性',
    surprise: '惊喜',
    fear: '恐惧',
    disgust: '厌恶',
    unknown: '未知'
}

const emotionColor = {
    happy: '#FFEAC5',
    angry: '#FF8899',
    sad: '#C1D1E2',
    neutral: '#EFFBD4',
    surprise: '#FFF2EA',
    fear: '#E5E1E8',
    disgust: '#E5EECF'
}
// 分页
const currentPage = ref(1)
const pageSize = ref(10)
const handleCurrentChange = (newPage) => {
    currentPage.value = newPage
}

const handleSizeChange = (newSize) => {
    pageSize.value = newSize
    currentPage.value = 1
}
const tableData = ref([])

const fetchTableData = async () => {
    try {
        const response = await axios.get('http://localhost:8181/uploadRecord/getOnlyRecordList', {
            headers: {
                [localStorage.getItem('tokenName')]: localStorage.getItem('tokenValue')
            }
        })
        if (response.data.code === 200) {
            // 提取uploadDate，并排序
            const list = (response.data.data || []).map(item => ({
                id: item.recordId,
                userId: item.userId,
                name: item.name,
                userId: item.userId,
                image: item.fileUrl,
                fileType: item.fileType,
                uploadDate: item.uploadTime ? item.uploadTime.slice(0, 10) : '',
                uploadTime: item.uploadTime,
                emotion_type: item.emotionType ? item.emotionType : 'unknown'
            }))
            // 按uploadTime倒序
            list.sort((a, b) => new Date(b.uploadTime) - new Date(a.uploadTime))
            tableData.value = list
        } else {
            ElMessage.error(response.data.message || '获取数据失败')
        }
    } catch (err) {
        ElMessage.error('获取数据失败')
        console.error(err)
    }
}

// 页面加载时获取数据
onMounted(() => {
    fetchTableData()
})

function getEmotionTagStyle(type) {
    return {
        backgroundColor: emotionColor[type] || '#EBEDF0',
        color: '#333',
        border: 'none'
    }
}

// 新增：筛选相关的响应式变量
const filterId = ref('')
const filterEmotion = ref('')
const multipleSelection = ref([])
const currentRecord = ref(null)

// 修改filteredTableData为响应式
const filteredTableData = computed(() => {
    return tableData.value.filter(item => {
        const matchId = filterId.value ? String(item.id).includes(filterId.value) : true
        const matchEmotion = filterEmotion.value ? item.emotion_type === filterEmotion.value : true
        return matchId && matchEmotion
    })
})

// 查询按钮
function handleQuery() {
    // 只需触发 filteredTableData 重新计算即可
    // 如果有分页，建议重置到第一页
    currentPage.value = 1
}

// 重置按钮
function handleReset() {
    filterId.value = ''
    filterEmotion.value = ''
    currentPage.value = 1
}

// 多选
function handleSelectionChange(val) {
    multipleSelection.value = val
}

// 删除单条
function handleDelete(row) {
    ElMessageBox.confirm('确定要删除该条记录吗？', '提示', { type: 'warning' })
        .then(() => {
            const idx = tableData.value.findIndex(item => item.id === row.id)
            if (idx !== -1) {
                tableData.value.splice(idx, 1)
                ElMessage.success('删除成功')
            }
        })
}

// 批量删除
function handleBatchDelete() {
    if (multipleSelection.value.length === 0) return
    ElMessageBox.confirm('确定要删除选中的记录吗？', '提示', { type: 'warning' })
        .then(() => {
            const ids = multipleSelection.value.map(item => item.id)
            for (let i = tableData.value.length - 1; i >= 0; i--) {
                if (ids.includes(tableData.value[i].id)) {
                    tableData.value.splice(i, 1)
                }
            }
            multipleSelection.value = []
            ElMessage.success('批量删除成功')
        })
}
const router = useRouter()

const showEmotion = (user) => {
    localStorage.setItem('userId', user.userId)
    router.push('/user/personalEmotion')
}
// 查看
const md = new MarkdownIt()
const dialogContentHtml = ref('') // 用于存储渲染后的html
const formattedReport = ref('')
const dialogRadarRef = ref(null)

async function viewRecord(row) {
    currentRecord.value = row
    dialogVisible.value = true

    // 通过记录id查询分析结果
    try {
        const res = await axios.get(`http://localhost:8181/EmoAnalyze/getByRDId/${row.id}`)
        if (res.data.code === 200 && Array.isArray(res.data.data) && res.data.data.length > 0) {
            // 取第一条分析结果
            row.emotionReport = res.data.data[0]
        } else {
            row.emotionReport = null
        }
    } catch (err) {
        row.emotionReport = null
    }

    // markdown渲染
    let content = row?.emotionReport?.analyze_content
    if (content && typeof content === 'string') {
        content = content.replace(/^<answer>\s*/i, '').replace(/\s*<\/answer>$/i, '')
        dialogContentHtml.value = md.render(content)
        formattedReport.value = JSON.stringify(row.emotionReport, null, 2)
    } else {
        dialogContentHtml.value = ''
        formattedReport.value = '暂无分析报告'
    }

    // 等待弹窗DOM渲染后再画雷达图
    nextTick(() => {
        renderDialogRadarChart()
    })
}


let dialogRadarInstance = null
function renderDialogRadarChart() {
    if (!dialogRadarRef.value) return
    if (!dialogRadarInstance) {
        dialogRadarInstance = echarts.init(dialogRadarRef.value)
    }
    const emo = currentRecord.value?.emotionReport || {}
    const data = [
        emo.angry ?? 0,
        emo.disgust ?? 0,
        emo.surprise ?? 0,
        emo.happy ?? 0,
        emo.fear ?? 0,
        emo.sad ?? 0,
        emo.neutral ?? 0
    ]
    dialogRadarInstance.setOption({
        tooltip: {},
        radar: {
            indicator: [
                { name: '愤怒', max: 1 },
                { name: '厌恶', max: 1 },
                { name: '惊喜', max: 1 },
                { name: '开心', max: 1 },
                { name: '恐惧', max: 1 },
                { name: '悲伤', max: 1 },
                { name: '中性', max: 1 }
            ],
            radius: '70%',
            name: { textStyle: { fontSize: 13 } }
        },
        series: [{
            type: 'radar',
            data: [{
                value: data,
                name: '情绪分布',
                areaStyle: { color: 'rgba(66,133,244,0.2)' },
                lineStyle: { color: '#4285f4', width: 2 },
                symbol: 'circle',
                itemStyle: { color: '#4285f4', borderColor: '#4285f4', borderWidth: 2 }
            }]
        }]
    })
}

// 弹窗关闭时销毁弹窗雷达图实例
watch(dialogVisible, (val) => {
    if (!val && dialogRadarInstance) {
        dialogRadarInstance.dispose()
        dialogRadarInstance = null
    }
})
</script>

<style scoped>
body,
html {
    height: 100%;
    margin: 0;
    padding: 0;
}

.title1 {
    display: flex;
    align-items: center;
    gap: 8px;
}

.latest-emotion-page {
    min-height: 100vh;
}

.bottom-section {
    background: #fff;
    border-radius: 8px;
    margin-bottom: 20px;
}

.analysis-records-container {
    width: 1471px;
    min-height: 200px;
    background: white;
    border-radius: 12px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
    padding: 30px;
    display: flex;
    align-items: flex-start;
    justify-content: center;
    flex-direction: column;
}

.single-line-img {
    display: flex;
    align-items: center;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    height: 40px;
}

.emo-detail-content {
    width: 100%;
    padding: 10px 0 0 0;
    display: flex;
    flex-direction: column;
    align-items: stretch;
}

.emo-detail-content2 {
    width: 100%;
    padding: 10px 0 0 0;
    display: flex;
    flex-direction: column;
    align-items: stretch;
    font-size: 16px;
}

.emo-row {
    display: flex;
    align-items: flex-start;
    margin-bottom: 28px;
}

.emo-row-top {
    display: flex;
    justify-content: flex-start;
    gap: 120px;
}

.emo-row-top .emo-col {
    display: flex;
    align-items: center;
    min-width: 260px;
}

.emo-detail-label {
    /* 固定宽度 */
    flex-shrink: 0;
    color: #333;
    font-weight: 500;
    text-align: left;
}

.emo-detail-value {
    flex: 1;
    min-width: 0;
    color: #222;
    margin-left: 6px;
}

.emo-row-img {
    gap: 40px;
}

.emo-img-col,
.emo-radar-col {
    display: flex;
    flex-direction: row;
    align-items: flex-start;
}

.emo-img-box {
    background: #f5f5f5;
    border: 1px solid #eee;
    width: 200px;
    height: 100px;
    display: flex;
    align-items: center;
    justify-content: center;
}

.emo-img-box2 {
    background: #f5f5f5;
    border: 1px solid #eee;
    width: 260px;
    height: 220px;
    /* 建议加上固定高度，便于图片充满 */
    display: flex;
    justify-content: center;
    align-items: center;
}

.emo-img-box img {
    max-width: 100%;
    max-height: 100%;
}

.emo-img-box2 img {
    width: 100%;
    height: 100%;
    object-fit: cover;
}

.emo-radar-box {
    margin-top: 8px;
}

.emo-radar-placeholder {
    width: 260px;
    height: 220px;
    background: #f5f5f5;
    border: 1px solid #eee;
    display: flex;
    align-items: center;
    justify-content: center;
}

.emo-detail-row {
    display: flex;
    align-items: flex-start;
    margin-bottom: 22px;
    font-size: 15px;
}

.emo-detail-report {
    align-items: flex-start;
}

.emo-json {
    font-family: "Consolas", "Menlo", "Monaco", monospace;
    font-size: 13px;
    background: #fafbfc;
    border: 1px solid #e4e7ed;
    border-radius: 4px;
    padding: 10px;
    margin: 0;
    width: 700px;
    max-width: 700px;
    min-height: 300px;
    max-height: 380px;
    overflow: auto;
    white-space: pre-wrap;
    word-break: break-all;
}

.emo-rich-content {
    font-size: 14px;
    background: #fafbfc;
    border: 1px solid #e4e7ed;
    border-radius: 4px;
    overflow: auto;
    word-break: break-all;
    line-height: 1.7;
    width: 98%;
    min-height: 300px;
    max-height: 380px;
}

.emo-rich-content h3,
.emo-rich-content h4 {
    margin: 8px 0 4px 0;
    font-weight: bold;
}

.emo-rich-content ul,
.emo-rich-content ol {
    margin: 6px 0 6px 18px;
}

.emo-rich-content p {
    margin: 4px 0;
}

.emo-detail-btn {
    display: flex;
    justify-content: center;
    margin-top: 18px;
}

.emo-detail-btn2 {
    display: flex;
    justify-content: center;
    margin-top: 18px;
}

::v-deep(.el-dialog__header) {
    text-align: center;

}

::v-deep(.el-dialog__wrapper) {
    display: flex !important;
    align-items: center;
    justify-content: center;
}

.pagination-container {
    margin-top: 30px;
    display: flex;
    justify-content: flex-end;
}

.box-card {
    background: #fff;
    border-radius: 8px;
    margin-bottom: 20px;
}

.table-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 12px 20px;
}

.query-card .card-header {
    font-weight: 600;
    font-size: 16px;
    color: #303133;
}

.filter-section {
    display: flex;
    align-items: center;
    gap: 20px;
    flex-wrap: wrap;
}

.pagination-container {
    margin-top: 30px;
    display: flex;
    justify-content: flex-end;
}

.filter-item {
    display: flex;
    align-items: center;
    gap: 10px;
}

.action-buttons {
    margin-left: auto;
    display: flex;
    gap: 10px;
}

.table-scroll-wrapper {
    max-height: 540px;
    overflow-y: auto;
    /* 新增：限制表格滚动区域高度 */
}

.table-scroll-wrapper::-webkit-scrollbar {
    width: 8px;
    /* 滚动条宽度 */
}

.table-scroll-wrapper::-webkit-scrollbar-thumb {
    background-color: #dcdcdc;
    border-radius: 4px;
}

.table-scroll-wrapper::-webkit-scrollbar-track {
    background-color: #f1f1f1;
}
</style>